package anji.plus.system.mark.base;

import anji.plus.system.mark.response.ResponseResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * <p>
 * 通用请求处理
 * </p>
 *
 * @author zag
 * @since 2023/7/14
 */
public abstract class BaseController<T extends BaseDomain,S extends IBaseService<T>> {


    @Resource
    protected HttpServletRequest request;

    public abstract S getService();

    /**
     * 新增
     * @param domain 领域模型
     * @return {@link ResponseResult}
     */
    @PostMapping("create")
    public ResponseResult create(@Valid @RequestBody T domain) {
        // 业务逻辑
        boolean created = getService().create(domain);
        if (created) {
            return ResponseResult.success("创建成功");
        }
        return null;
    }

    /**
     * 删除
     * @param Id {@code Long}
     * @return {@link ResponseResult}
     */
    @DeleteMapping("remove/{Id}")
    public ResponseResult remove(@PathVariable Long Id) {
        // 业务逻辑
        boolean deleted = getService().remove(Id);
        if (deleted) {
            return ResponseResult.success("删除成功");
        }
        return ResponseResult.failure();
    }

    /**
     * 修改
     * @param domain 领域模型
     * @return {@link ResponseResult}
     */
    @PutMapping("update")
    public ResponseResult update(@Valid @RequestBody T domain) {
        // 业务逻辑
        boolean updated = getService().update(domain);
        if (updated) {
            return ResponseResult.success("编辑成功");
        }
        return ResponseResult.failure();
    }

    /**
     * 获取
     * @param Id {@code Long}
     * @return {@link ResponseResult}
     */
    @GetMapping("get/{Id}")
    public ResponseResult get(@PathVariable Long Id) {
        // 业务逻辑
        T domain = getService().get(Id);
        return ResponseResult.success(domain);
    }

    /**
     * 分页
     * @param current {@code int} 页码
     * @param size {@code int} 笔数
     * @param domain 领域模型
     * @return {@link ResponseResult}
     */
    @GetMapping("page")
    public ResponseResult page(@RequestParam int current, @RequestParam int size, @ModelAttribute T domain) {
        IPage<?> page = getService().page(current, size, domain);
        return ResponseResult.success(page);
    }

}
